<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\GoodsPicModel;
use App\Utils\ResponseEnum;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Intervention\Image\ImageManager;

class AutoController extends ApiController
{
    const IMAGE_SIZE = 0;
    const IMAGE_LIMIT = 20;

    /**
     * 自动获取单张图片尺寸
     * @return JsonResponse
     */
    public function getImageSize(): JsonResponse
    {
        $goodsImage = GoodsPicModel::where('width', self::IMAGE_SIZE)->where('IsVideo', 0)->first();
        if ($goodsImage) {
            echo $goodsImage->ID;
            $goodsImage = $this->getImageSizeData($goodsImage);
            $goodsImage->save();
        }
        return $this->success();
    }

    /**
     * 自动获取产品组图尺寸（分页）
     * @param Request $request
     * @return JsonResponse
     */
    public function getGoodsImagesSize(Request $request): JsonResponse
    {
        if ($request->input('id'))
            $id = $request->input('id');
        else
            $id = GoodsPicModel::where('PID', 0)->where('width', self::IMAGE_SIZE)->value('ID');
        echo $id;
        $imageList = GoodsPicModel::where('width', self::IMAGE_SIZE)->where('PID', $id)->where('IsVideo', 0)->orderByDesc('ID')->limit(self::IMAGE_LIMIT)->get();
        foreach ($imageList as $goodsImage) {
            $goodsImage = $this->getImageSizeData($goodsImage);
            $goodsImage->save();
        }
        return $this->success();
    }

    /**
     * 解析图片尺寸
     * @param $goodsImage
     * @return mixed
     */
    private function getImageSizeData($goodsImage): mixed
    {
        $ImageManager = new ImageManager();
        try {
            $image = $ImageManager->make(Controller::getImageFullUrl($goodsImage));
            $goodsImage->width = $image->width();
            $goodsImage->height = $image->height();
        } catch (\Exception $e) {
            $goodsImage->width = 1;
            $goodsImage->height = 1;
        }
        return $goodsImage;
    }
}
